' 设置当前目录
Dim fso, folder, currentDir
Set fso = CreateObject("Scripting.FileSystemObject")
currentDir = fso.GetAbsolutePathName(".")

' 创建Word应用程序对象
Dim wordApp
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = False

' 递归处理当前目录及其子目录下的所有.doc和.docx文件
ProcessFolder currentDir

' 关闭Word应用程序
wordApp.Quit
Set wordApp = Nothing

' 定义递归处理函数
Sub ProcessFolder(folderPath)
    Dim folder, subFolder, file
    Set folder = fso.GetFolder(folderPath)

    ' 处理当前文件夹下的所有文件
    For Each file In folder.Files
        If LCase(fso.GetExtensionName(file.Name)) = "doc" Or LCase(fso.GetExtensionName(file.Name)) = "docx" Then
            ConvertFileToPdf file.Path, Replace(file.Path, "." & fso.GetExtensionName(file.Path), ".pdf")
        End If
    Next

    ' 递归处理当前文件夹下的所有子文件夹
    For Each subFolder In folder.SubFolders
        ProcessFolder subFolder.Path
    Next
End Sub

' 定义转换函数
Sub ConvertFileToPdf(inputFile, outputFile)
    On Error Resume Next
    Dim doc
    Set doc = wordApp.Documents.Open(inputFile)
    If Err.Number <> 0 Then
        WScript.Echo "Failed to open file: " & inputFile & " with error code: " & Err.Number
        Err.Clear
        Exit Sub
    End If

    ' 使用SaveAs2方法保存为PDF格式
    doc.SaveAs2 outputFile, 17 ' 17 is the PDF format constant for SaveAs2 method
    If Err.Number <> 0 Then
        WScript.Echo "Conversion failed for file: " & inputFile & " with error code: " & Err.Number
        Err.Clear
    Else
      '  WScript.Echo "Successfully converted " & inputFile & " to " & outputFile
    End If

    doc.Close False
    Set doc = Nothing
End Sub